package com.topscomm.file;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import com.topscomm.basic.exception.ServiceException;

import lombok.extern.slf4j.Slf4j;

/**
 * ffmpeg命令相关
 *
 * @description:
 * @author: donghang
 * @date: 2020年8月20日上午9:20:01
 * @modify:
 */
@Slf4j
public class FFmpegCommand extends BaseCommand {

	public FFmpegCommand(List<String> command) {
		super(command);
	}

	/**
	 * ffmpeg执行命令
	 *
	 * @description:
	 * @param callback
	 * @return
	 * @author: donghang
	 * @throws InterruptedException
	 * @date: 2020年8月20日上午9:21:12
	 * @modify:
	 */
	@Override
	public synchronized CommandResult executeCommand() {
		StringBuffer strResult = new StringBuffer();
		try {
			ProcessBuilder builder = new ProcessBuilder();
			builder.command(this.commandList);
			log.debug("执行ffmpeg命令" + this.commandList.toString());
			// 正常信息和错误信息合并输出
			builder.redirectErrorStream(true);
			// 开启执行子线程
			Process process = builder.start();
			// 开启线程异步读取，防止线程阻塞
			new Thread(new Runnable() {
				@Override
				public void run() {
					BufferedReader bufferReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
					String line = null;
					try {
						while ((line = bufferReader.readLine()) != null) {
							strResult.append(line);
							strResult.append(" ");
						}
						if (bufferReader != null) {
							bufferReader.close();
						}
					} catch (IOException e) {
						throw new ServiceException(e.getMessage());
					}

				}

			}).start();
			// 等待命令子线程执行完成
			int exitValue = process.waitFor();
			CommandResult result = new CommandResult();
			result.setSuccess(true);
			result.setMsg(strResult.toString());
			process.destroy();
			return result;
		} catch (IOException e) {
			throw new ServiceException(e.getMessage());
		} catch (InterruptedException e) {
			//中断退出
			Thread.currentThread().interrupt();
			throw new ServiceException("线程阻塞异常:" + e.getMessage());
		}
	}
}
